/*
 * @Author: zhangxiangsheng 1026583651@qq.com
 * @Date: 2024-06-17 14:55:58
 * @LastEditors: zhangxiangsheng 1026583651@qq.com
 * @LastEditTime: 2024-06-20 15:45:19
 * @FilePath: \appGly\z\function\$t.js
 * @Description:
 *
 * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved.
 */
import i18n from "@/locale/index.js";
import store from "@/store/index.js";

export default function $t() {
  if (arguments.length == 0) {
    return "";
  }
  if (store.getters["user/langg"] == "zh") {
    let str = String(arguments[0]);

    if (!str || str == "undefined" || str == "") {
      return "";
    }
    let array = arguments;
    // console.log(str);
    for (let i = 1; i <= array.length - 1; i++) {
      let pattern = `\\{${i - 1}\\}`;
      let regex = new RegExp(pattern);
      str = str.replace(regex, array[i]);
    }
    return str;
  }

  let str = String(arguments[0]);
  if (!str || str == "undefined") {
    return arguments[0];
  }
  let resultString = "";
  let matchedArray = [];
  // 正则表达式匹配数字和字母
  let pattern = /[:,,，0-9a-zA-Z.\-/ ]+(?![^{]*})/g;
  if (!str.includes("{0}")) {
    // 定义一个替换函数，用于返回不同的替换值
    function replacement(match) {
      return "{" + replacement.counter++ + "}";
    }

    // 将替换函数的计数器初始化为0
    replacement.counter = 0;
    resultString = str.replace(pattern, replacement);
    // 使用match方法获取匹配到的字符串数组
    matchedArray = str.match(pattern);
    matchedArray = matchedArray || [];
    str = resultString;
  }
  if (str == "" || String(arguments[0]).replace(pattern, "") == "") {
    return arguments[0];
  }
  let i18nstrs = uni.getStorageSync("i18n") || [];
  // console.log(i18nstrs);
  if (i18n.te(str)) {
    str = i18n.t(str);
  } else if (
    !i18nstrs.find(function (e) {
      return e == str;
    })
  ) {
    i18nstrs.push(str);
    uni.setStorageSync("i18n", i18nstrs);
  }
  if (i18nstrs.length != 0) {
    // console.log(JSON.stringify(i18nstrs), "i18nstrs");
  }
  //

  let array = [...arguments].slice(1);
  array = [str, ...matchedArray, ...array];
  // console.log(array, "123", str);
  for (let i = 1; i <= array.length - 1; i++) {
    let pattern = `\\{${i - 1}\\}`;
    let regex = new RegExp(pattern);

    str = str.replace(regex, array[i]);
  }
  // console.log(str);
  return str;
}
